import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import electron from 'vite-electron-plugin'
import { customStart } from 'vite-electron-plugin/plugin'
import path from 'path'
import { builtinModules } from 'module'

export default defineConfig({
  plugins: [
    vue(),
    electron({
      include: ['electron', 'src/preload.js'],
      transformOptions: {
        sourcemap: !!process.env.VSCODE_DEBUG,
      },
      plugins: [
        customStart(({ startup }) => {
          if (process.env.VSCODE_DEBUG) {
            console.log('[startup] Electron App')
          } else {
            startup()
          }
        }),
      ],
    }),
  ],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src')
    }
  },
  base: './', // 确保使用相对路径
  build: {
    outDir: 'dist',
    emptyOutDir: true,
    rollupOptions: {
      input: {
        main: path.resolve(__dirname, 'index.html'),
      },
      output: {
        entryFileNames: '[name].js',
        chunkFileNames: '[name].[hash].js',
        assetFileNames: '[name].[hash][extname]'
      },
      external: [
        ...builtinModules,
        ...builtinModules.map((m) => `node:${m}`),
        'electron',
        '@grpc/grpc-js',
        '@grpc/proto-loader',
        'protobufjs',
        'lodash.camelcase'
      ]
    },
    minify: 'esbuild',
    target: 'esnext',
    cssTarget: 'chrome61',
    assetsInlineLimit: 4096,
    sourcemap: false,
    reportCompressedSize: false,
  },
  esbuild: {
    legalComments: 'none',
    target: 'esnext',
    minify: true,
    minifyIdentifiers: true,
    minifySyntax: true,
    minifyWhitespace: true,
  },
  optimizeDeps: {
    exclude: ['electron'],
    include: ['@grpc/grpc-js', '@grpc/proto-loader', '@js-sdsl/ordered-map', '@protobufjs/base64', 'lodash.camelcase', 'protobufjs']
  }
})